﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.Web.Mvc;
using System.Web;
using System.Web.Routing;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.UI;

namespace Sparrow.CMS.WebFormTemplate
{
    public class ViewEngine:IViewEngine
    {
        #region IViewEngine Members

        public IEnumerable<Widget> GetWidgets(Layout layout)
        {
            var viewFullName = VirtualPathUtility.ToAbsolute(layout.Name);

            var widgets = new List<Widget>();
            using (StreamReader reader = File.OpenText(viewFullName))
            {
                var html = reader.ReadToEnd();
                Regex re = new Regex("<%=[ ]?Html.RenderWidget\\(this\\.Model\\.(?<widget>[\\w]+)\\)[ ]?%>", RegexOptions.None);
                MatchCollection mc = re.Matches(html);
                foreach (Match ma in mc)
                {
                    Widget widget = new Widget()
                    {
                        Layout = layout,
                        Name = ma.Groups["widget"].Value
                    };

                    widgets.Add(widget);
                }

            }
            //<%=[ ]?Html.RenderWidget\(this\.Model\.[\w]+\)[ ]?%>

            return widgets;

        }

        public string RenderView(string viewName, PageContent content, object model)
        {
            var viewPath = VirtualPathUtility.ToAbsolute(viewName);

            WebFormView view = new WebFormView(viewPath);         
      

            var tempData = new TempDataDictionary();
            tempData.Add("PageContent", content);

            StringBuilder sb = new StringBuilder();
            StringWriter st = new StringWriter(sb);
            HtmlTextWriter writer = new HtmlTextWriter(st);

            var contoller = new EmptyController();
            var context = HttpContext.Current.Request.RequestContext;

            var contollerContext = new ControllerContext(context, contoller);

            ViewContext viewContext = new ViewContext(contollerContext, view, new ViewDataDictionary(model), tempData, writer);
            view.Render(viewContext, writer);

            return sb.ToString();

        }

        #endregion
    }



    [Export(".ascx",typeof(IViewEngine))]
    [PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.Shared)]
    public class AscxViewEngine : ViewEngine
    {
    }

    [Export(".aspx", typeof(IViewEngine))]
    [PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.Shared)]
    public class AspxViewEngine : ViewEngine
    {
    }
}
